import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_trip/dao/home_dao.dart';
import 'package:flutter_trip/model/common_model.dart';
import 'package:flutter_trip/model/grid_nav_model.dart';
import 'package:flutter_trip/model/home_model.dart';
import 'package:flutter_trip/model/sales_box_model.dart';
import 'package:flutter_trip/pages/search_page.dart';
import 'package:flutter_trip/pages/speak_page.dart';
import 'package:flutter_trip/plugin/splash_plugin.dart';
import 'package:flutter_trip/util/navigator_util.dart';
import 'package:flutter_trip/widget/grid_nav.dart';
import 'package:flutter_trip/widget/loading_container.dart';
import 'package:flutter_trip/widget/local_nav.dart';
import 'package:flutter_trip/widget/sales_box.dart';
import 'package:flutter_trip/widget/sub_nav.dart';
import 'package:flutter_trip/widget/webview.dart';
import 'package:flutter_trip/widget/search_bar.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

const APPBAR_SCROLL_OFFSET = 50;
const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';

class _HomePageState extends State<HomePage> {
//  List _imageUrls = [
//    'https://picsum.photos/250?image=1',
//    'https://picsum.photos/250?image=2',
//    'https://picsum.photos/250?image=3',
//  ];
  double appBarAlpha = 0;
  String resultString = '';
  List<CommonModel> localNavList = [];
  List<CommonModel> subNavList = [];
  List<CommonModel> bannerList = [];
  GridNavModel gridNavModel;
  SalesBoxModel salesBoxModel;
  bool _loading = true;

  _onScroll(offset) {
//    print(offset);
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
//    print(appBarAlpha);
  }

  Future<Null> _handleRefresh() async {
//    HomeDao.fetch().then((result){
//      setState(() {
//        resultString = json.encode(result);
//      });
//    }).catchError((e){
//      setState(() {
//        resultString = e.toString();
//      });
//    });

    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        resultString = json.encode(model);
        localNavList = model.localNavList;
        subNavList = model.subNavList;
        bannerList = model.bannerList;
        gridNavModel = model.gridNav;
        salesBoxModel = model.salesBox;
//        print('gridNavModel：' + gridNavModel.toString());
//        print('_localNavList：' + localNavList.toString());
        _loading = false;
      });
    } catch (e) {
      setState(() {
        resultString = e.toString();
        _loading = false;
      });
    }
    return null;
  }

  @override
  void initState() {
    super.initState();
    _handleRefresh();

    hideScreen();
  }

  ///hide your splash screen
  Future<void> hideScreen() async {
    Future.delayed(Duration(milliseconds: 600), () {
      SplashPlugin.hide();
    });
  }

  @override
  Widget build(BuildContext context) {
    return LoadingContainer(
      isLoading: _loading,
      child: Scaffold(
          backgroundColor: Color(0xfff2f2f2),
          body: Stack(
            children: <Widget>[
              MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: RefreshIndicator(
                    onRefresh: _handleRefresh,
                    child: NotificationListener(
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollUpdateNotification &&
                            scrollNotification.depth == 0) {
                          // 滚动且是列表滚动的时候
                          _onScroll(scrollNotification.metrics.pixels);
                        }
                      },
                      child: _listView,
                    ),
                  )),
              _appBar
            ],
          )),
    );
  }

  Widget get _listView {
    return ListView(
      children: <Widget>[
        _banner,
        Padding(
          padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
          child: LocalNav(
            localNavList: localNavList,
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: GridNav(
            gridNavModel: gridNavModel,
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SubNav(
            subNavList: subNavList,
          ),
        ),
        Padding(
          padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
          child: SalesBox(
            salesBox: salesBoxModel,
          ),
        ),
//      Container(
//        height: 800,
//        child: Text(resultString),
//      )
      ],
    );
  }

  Widget get _appBar {
//    return Opacity(
//      opacity: appBarAlpha,
//      child: Container(
//        height: 60,
//        decoration: BoxDecoration(color: Colors.white),
//        child: Center(
//          child: Padding(
//            padding: EdgeInsets.only(top: 20),
//            child: Text('首页'),
//          ),
//        ),
//      ),
//    );

    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
            //appbar渐变遮罩背景
            colors: [Color(0x66000000), Colors.transparent],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          )),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
                color:
                    Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255)),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  Widget get _banner {
    return Container(
      height: 160,
      child: Swiper(
//       itemCount: _imageUrls.length,
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
//              Navigator.push(context, MaterialPageRoute(builder: (context) {
//                CommonModel model = bannerList[index];
//                return WebView(
//                  url: model.url,
//                  title: model.title,
//                  hideAppBar: model.hideAppBar,
//                );
//              }));
              CommonModel model = bannerList[index];
              NavigatorUtil.push(context, WebView(
                url: model.url,
                title: model.title,
                hideAppBar: model.hideAppBar,
              ));
            },
            child: Image.network(
//             _imageUrls[index],
              bannerList[index].icon,
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  void _jumpToSearch() {
//    Navigator.push(context, MaterialPageRoute(
//      builder: (context){
//        return SearchPage(
//          hint:SEARCH_BAR_DEFAULT_TEXT,
//        );
//      }
//    ));
    NavigatorUtil.push(context, SearchPage(
      hint:SEARCH_BAR_DEFAULT_TEXT,
    ));
  }

  void _jumpToSpeak() {
//    Navigator.push(context, MaterialPageRoute(
//        builder: (context){
//          return SpeakPage();
//        }
//    ));
    NavigatorUtil.push(context, SpeakPage());
  }
}
